package com.xy6.concurrencyart.chapter03;

/**
 * Final示例
 * 
 * @author zhang
 * @since 2018-05-23
 */
public class FinalReferenceEscapeExample {
	final int i;
	static FinalReferenceEscapeExample obj;

	public FinalReferenceEscapeExample() {
		// 写final域
		i = 1;
		// this引用在此"逸出"
		obj = this;
	}

	public static void writer() {
		new FinalReferenceEscapeExample();
	}

	public static void reader() {
		if (obj != null) {
			int temp = obj.i;
			System.out.println(temp);
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		for(int i=0; i<1000; i++){
			Thread t1 = new Thread(new Runnable(){
				@Override
				public void run(){
					FinalReferenceEscapeExample.writer();
				}
			});
			Thread t2 = new Thread(new Runnable(){
				@Override
				public void run(){
					FinalReferenceEscapeExample.reader();
				}
			});
			t1.start();
			t1.join();
			t2.start();
			t2.join();
		}

	}
}
